<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>打开文件夹</title>
  </head>
  <body>
    <button id="openDir">打开文件夹</button>
    <script>
      const openDir = document.getElementById('openDir');
      async function processHandle(handle) {
        if (handle.kind === 'file') {
          return handle;
        }
        handle.children = [];
        // 获得异步迭代器
        const ite = handle.entries();
        for await (const item of ite) {
          handle.children.push(await processHandle(item[1]));
        }
        return handle;
      }
      openDir.addEventListener('click', function (e) {
        // 选择文件夹
        window
          .showDirectoryPicker()
          .then(async (handle) => {
            const root = await processHandle(handle);
            console.log(root);
          })
          .catch((error) => {
            // 用户拒绝的处理
            console.log(error);
          });
      });
    </script>
  </body>
</html>
